﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleSocket
{
    /// <summary>
    /// Used to build up parts of data that we receive from the socket.
    /// </summary>
    internal class MessagePartReceiver
    {
        private int length = 0;

        /// <summary>
        /// The total length of the message that we are receiving
        /// </summary>
        public int Length
        {
            get
            {
                return length;
            }
            
            set
            {
                length = value;
                Reset();
            }
        }

        /// <summary>
        /// Data Buffer the size of Length
        /// </summary>
        public byte[] Data { get; private set; }

        /// <summary>
        /// If true the Data is retrival is complete.
        /// </summary>
        public bool Complete { get; private set; }
        
        private int BytesCompleted { get; set; }

        public MessagePartReceiver(int length)
        {
            Length = length;
            Reset();
        }

        public void Reset()
        {
           Data = new byte[Length];
           BytesCompleted = 0;
           Complete = false;
        }

        /// <summary>
        /// Reads data from a common buffer.
        /// </summary>
        /// <param name="bytesReceived">bytes received into the buffer</param>
        /// <param name="buffer">buffer that we are reading the data from</param>
        /// <param name="position">the current position that we should read in the buffer.</param>
        public void ReadData(int bytesReceived, byte[] buffer, ref int position)
        {
            if (Complete)
                return;

            int bytesLeftToRead = bytesReceived - position;

            int read = (Length - BytesCompleted);

            if (bytesLeftToRead < read)
                read = bytesLeftToRead;

            Array.Copy(buffer, position, Data, BytesCompleted, read);
            BytesCompleted += read;
            position += read;

            if (BytesCompleted == Length)
                Complete = true;
        }
    }
}
